package com.company.cloud.gateway.component.filter.pre;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginUserInfo;
import com.company.cloud.common.constant.CommonConstant;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.gateway.component.service.AuthCheckService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import cn.hutool.extra.servlet.ServletUtil;
import lombok.extern.log4j.Log4j2;

@Log4j2
@Component
public class UserAuthFilter extends ZuulFilter {
	
	
	@Autowired
	private AuthCheckService authCheckService;
	
	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		return FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER;
	}

	
	
	@Override
	public Object run() throws ZuulException {
		log.info("+++++ZuulFilter -> UserAuthFilter -> filterOrder={}", "0");
		RequestContext ctx= RequestContext.getCurrentContext();
		HttpServletRequest request= ctx.getRequest();
		
		String 	servletPath=request.getServletPath();
		String  contextPath=request.getContextPath();
		
		String token=request.getHeader(CommonConstant.TOKEN_HEADER);
		log.info("++++++++ servletPath={},contextPath={},token={}",servletPath,contextPath, token);
//		
//		try {
//			LoginUserInfo user= authCheckService.check(servletPath, contextPath, token);
//			if(user!=null) {
//				user.setIp(ServletUtil.getClientIP(request));
//				ctx.addZuulRequestHeader(CommonConstant.USER_HEADER, AuthContextUtils.getUserBase64(user));
//			}
//			return null;
//		} catch (BusinessException e) {
//			System.out.println("+++++++认证失败!!!"+e.getMessage());
//			ctx.setSendZuulResponse(false);
//			ctx.set("isSuccess", false);
//			BaseResult result= BaseResult.error(e.getCode(), e.getMessage());
//			ctx.setResponseBody(JSON.toJSONString(result));
//			ctx.getResponse().setContentType("application/json; charset=utf-8");
//			return null;
//		}
		
		return null;
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

}
